datetime
取得時間資訊
now()
方法獲取當前時間strftime
格式化日期strptime
將字串轉時間date
取得日期time
取得時間timedelta
這篇文章是閱讀Asabeneh的30 Days Of Python: Day 16 - Python Date time後的學習筆記與心得。
使用Python內建的datetime
模組,可以取得日期與時間的資訊;類似JavaScript中的Date物件。
這篇文章會介紹到date、datetime、time,以及timedelta。
datetime
的屬性清單可使用dir()
函式取得:import datetime
print(dir(datetime))
datetime
取得時間資訊透過給datetime
參數,可以得到一個datetime
類別(class),其下有日期與時間相關的屬性和方法可供取用。
語法:datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
參數值範圍:
fold in [0, 1]
fold
用在有日光節約時間一類時間有重疊的狀況,協助判斷是用調整前還是調整後的時間為標準(非自動調整)。tzinfo
這個類別(class)是用來幫助標示時區資訊。
以上兩個物件不會在這章節討論到
from datetime import datetime
moon_festival = datetime(2022, 9, 10)
print(moon_festival) # 2022-09-10 00:00:00
day = moon_festival.day
month = moon_festival.month
year = moon_festival.year
hour = moon_festival.hour
minute = moon_festival.minute
second = moon_festival.second
timestamp = moon_festival.timestamp()
print(year, month, day, hour, minute, timestamp)
# 2022 9 10 0 0 1662739200.0
print(f'{year}/{month}/{day}, {hour}:{minute}')
# 2022/9/10, 0:0
now()
方法獲取當前時間from operator import attrgetter
from datetime import datetime
now = datetime.now()
print(now) # 2022-09-10 00:00:00
year, month, day, hour, minute, second, timestamp, timestamp = attrgetter("year", "month", "day", "hour", "minute", "second", "timestamp", "timestamp")(now)
print('timestamp:', timestamp())
# timestamp: 1662739200.0
print(f'{year}/{month}/{day}, {hour}:{minute}')
# 2022/9/10, 0:0
attrgetter
做的事跟JavaScript的解構賦值(destructuring assignment)相同 -- 參考這則回答
timestamp
回傳的是從1970/1/1開始計算到該日期時間的總秒數strftime
格式化日期前面例子印出的日期及時間是一步步把datetime
的屬性拿出來,再自行排列輸出,strftime
(string format time)函式則是可以接收格式參數,並給出符合格式的輸出值:
from datetime import datetime
moon_festival = datetime(2022, 9, 10, 8, 30, 27)
# hh:mm:ss
t = moon_festival.strftime("%H:%M:%S")
print("time:", t) # time: 13:30:27
# yyyy/mm/dd, hh:mm:ss
iso8601 = moon_festival.strftime("%Y/%m/%d, %H:%M:%S")
print("General:", iso8601) # General: 2022/09/10, 13:30:27
# dd/mm/yyyy hh:mm:ss
uk = moon_festival.strftime("%d/%m/%Y, %H:%M:%S")
print("UK:", uk) # UK: 10/09/2022, 13:30:27
strptime
將字串轉時間語法:strptime(date_string, format)
date_string
的部份是要被轉換的語法,format
則必須配合date_string
的形式撰寫對應的運算子:
from datetime import datetime
date_string = "24 December, 2021"
date_object = datetime.strptime(date_string, "%d %B, %Y")
print(date_object) # 2021-12-24 00:00:00
date
取得日期date
函式會回傳一個date object,帶有跟參數相同的年、月,和日的屬性;
語法:date(year, month, day)
所有的參數都是必需的,如果超出範圍的話會產生ValueError。
from datetime import date
d = date(2021, 12, 25)
print(d) # 2021-12-25
# date object of today's date
today = date.today()
print("Current date", today) # Current date 2022-09-21
print("Current year:", today.year) # Current year: 2022
print("Current month:", today.month) # Current month: 9
print("Current day:", today.day) # Current day: 21
today()
這個方法可以拿到今天的日期,不因date
中的參數有所影響。並且能透過year, month, day屬性分別拿到年、月,和日的值。time
取得時間語法:time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
所有的參數都是可選的(optional),並且值有範圍限制,傳入超出範圍的參數值會產生ValueError:
fold in [0, 1]
tzinfo
可以是None
或是tzinfo
子類(subclass)from datetime import time
a = time()
print("a =", a) # a = 00:00:00
b = time(10, 30, 50)
print("b =", b) # b = 10:30:50
c = time(hour=10, minute=30, second=50)
print("c =", c) # c = 10:30:50
d = time(10, 30, 50, 200555)
print("d =", d) # d = 10:30:50.200555
使用date
:
from datetime import date
today = date.today()
new_year = date(year=2023, month=1, day=1)
day_left_for_newyear = new_year - today
print("Day left for new year:", day_left_for_newyear)
# Day left for new year: 101 days, 0:00:00
使用datetime
:
from datetime import datetime
datetime_today = datetime.now()
datetime_new_year = datetime(year=2023, month=1, day=1, hour=0, minute=0, second=0)
time_left_for_newyear = datetime_new_year - datetime_today
print("Time left for new year:", time_left_for_newyear)
# Time left for new year: 100 days, 15:36:11.162186
timedelta
這個物件會顯示出兩日期/時間之間的差距。
語法:timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
參數只會保留days、seconds和microseconds,其他的會進行轉換:
後續表示會再依days、seconds和microseconds的範圍調整,超出範圍的話會產生OverflowError:
from datetime import timedelta
t1 = timedelta(weeks=12, days=10, hours=4, seconds=20)
print("t1 =", t1) # t1 = 94 days, 4:00:20
t2 = timedelta(days=7, hours=5, minutes=3, seconds=30)
print("t2 =", t2) # t2 = 7 days, 5:03:30
t3 = t1 - t2
print("t3 =", t3) # t3 = 86 days, 22:56:50